package com.example.factory;

import com.example.http.HttpRequestServer;
import com.example.model.FormMulit;
import com.example.socket.ServletRequest;
import com.example.socket.model.MulitiFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname ServletRequestFactory
 * @Description TODO
 * @Date 2023/4/28 15:50
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class ServletRequestFactory {

    public static ServletRequest getServletReqest(HttpRequestServer httpRequestServer){
        Map<String,String> queryString=httpRequestServer.getQueryMap();
        Map<String, List<String>> queryStringList=null;
        if(queryString!=null){
             queryStringList=new HashMap<>();
            for(Map.Entry<String,String> entry : queryString.entrySet()){
                if(!queryStringList.containsKey(entry.getKey())){
                    queryStringList.put(entry.getKey(),new ArrayList<>());
                }
                queryStringList.get(entry.getKey()).add(entry.getValue());
            }
        }
        Map<String, FormMulit> map=httpRequestServer.getMulitMap();
        if(map != null){
            Map<String,Object> from=new HashMap<>();
            for (Map.Entry<String, FormMulit> entry : map.entrySet()) {
                MulitiFile mulitiFile=new MulitiFile(entry.getValue().getFileName(),entry.getValue().getBytes(),entry.getValue().getFileType());
                from.put(entry.getKey(), mulitiFile);
            }
            if(httpRequestServer.getFormData()==null){
                httpRequestServer.setFormData(from);
            }else {
                httpRequestServer.getFormData().putAll(from);
            }
        }
        ServletRequest request=new ServletRequest(httpRequestServer.getPath(),
                httpRequestServer.getPath(),
                httpRequestServer.getRequestMethod(),
                httpRequestServer.getHeards(),
                httpRequestServer.getFormData(),
                queryStringList,
                httpRequestServer.getJson(),
                httpRequestServer.getInputStream(),
                httpRequestServer.getHeards().get("Content-Type")
                );
        return request;
    }
}
